/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Salesman.gui;

/**
 *
 * @author weinpau
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;

import com.l2fprod.common.swing.*;
import com.l2fprod.common.swing.plaf.misc.IconPackagerButtonBarUI;
import org.jdesktop.swingx.JXTitledPanel;

public class TabbedPanel extends JPanel {

    private JButtonBar button_bar = new JButtonBar(JButtonBar.VERTICAL);
    private ButtonGroup group = new ButtonGroup();
    private Component currentComponent;
    private String currentTitle;
    private int buttonCount = 0, selectedIndex;
    private EventListenerList listeners = new EventListenerList();

    public TabbedPanel() {

        setLayout(new BorderLayout());
        add("West", button_bar);
        button_bar.setUI(new IconPackagerButtonBarUI());
    }

    private void show(Component component) {
        if (currentComponent != null) {
            remove(currentComponent);
        }
        add("Center", currentComponent = component);
        revalidate();
        repaint();
    }

    public void addButton(final Component component, String title, ImageIcon icon) {

        final JToggleButton button = new JToggleButton();

        button.setText(title);
        button.setIcon(icon);

        final int selectedIndexFinal = buttonCount++;

        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                show(component);
                currentTitle = button.getText();
                selectedIndex = selectedIndexFinal;
                notifyAdvertisement(new ListSelectionEvent(this, selectedIndex, selectedIndex, true));
            }
        });

        button_bar.add(button);
        group.add(button);

        if (group.getSelection() == null) {
            button.setSelected(true);
            currentTitle = button.getText();
            show(component);
        }

    }

    public void addListSelectionListener(ListSelectionListener listener) {
        listeners.add(ListSelectionListener.class, listener);
    }

    private synchronized void notifyAdvertisement(ListSelectionEvent event) {
        for (ListSelectionListener l : listeners.getListeners(ListSelectionListener.class)) {
            l.valueChanged(event);
        }
    }

    public String getCurrentTitle() {
        return currentTitle;
    }

    public Component getCurrentComponent() {
        return currentComponent;
    }

    public int getSelectedIndex() {
        return selectedIndex;

    }

    public void setSelectedIndex(int index) {

        try {
            JToggleButton button = (JToggleButton) button_bar.getComponent(index);
            button.doClick();
            
        } catch (Exception excep) {
        }
    }
}
